from django.shortcuts import render, HttpResponse as response
from App.models import *

# Create your views here.


def add_person(request):
    try:
        p = PersonModel()
        p.name = "zhangsan"
        p.age = 20
        p.save()
        return response("Person added ok!")
    except Exception as e:
        return response("add failed!")


def add_person2(request):
    try:
        p = PersonModel(name="lisi", age=30)
        p.save()
        return response("Person added ok2 !")

    except Exception as e:
        return response("add failed2 !")


def add_person3(request):

    try:
        PersonModel.objects.create(name="wangwu", age=40)
        return response("Person added ok3 !")

    except Exception as e:
        return response("add failed3 !")


def add_person4(request):

    try:
        res = PersonModel.objects.get_or_create(name="zhaoliu", age=50)
        print(res)
        return response(res[0])
    except Exception as e:
        return response("add failed4 !")


def batch_add(request):
    try:
        for i in range(10, 21):
            PersonModel.objects.create(name=f"张{i}琳", age=i + 15)
        return response("Person added ok5 !")
    except Exception as e:
        return response("add failed5 !")


def del_person(request):
    try:
        # 删除第一条数据
        p = PersonModel.objects.first()
        p.delete()
        return response(p.name + " Person deleted ok !")

    except Exception as e:
        return response("del failed !")


def del_person2(request):
    try:
        # 删除age>35的数据
        PersonModel.objects.filter(age__gt=35).delete()
        return response("All Person deleted ok !")

    except Exception as e:
        return response("del failed !")


def update_person(request):
    try:
        p = PersonModel.objects.first()
        p.age = 666
        p.save()

        # p.save() 是把所有字段进行了更新
        # p.save(update_fields=["age"]) 仅更新age字段
        return response(p.name + " updated ok !" + str(p.age))

    except Exception as e:
        return response("update failed !")


def batch_update(request):
    try:
        PersonModel.objects.all().update(age=100)
        return response("All Person updated ok !")
    except Exception as e:
        return response("update failed !")


# get()只能获取到一条数据,如果有多条数据会报错,如果没有数据也会报错
# first(),last(),order_by(),filter()等方法可以获取多条数据,但是返回的是QuerySet对象,而不是具体的模型实例
def get_person(request):
    try:
        p = PersonModel.objects.get(id=6)
        return response(p.name + " got ok !")
    except Exception as e:
        return response("id 1 get failed !")
